<template>
  <div class="ps-r preview-report" v-loading="isLoading">
    <div class="mr-center preview-container">
      <div class="preview-header" v-if="isEditPath">
        <div class="text-c preview-report-title">{{ layoutData.title }}</div>
      </div>
      <el-form
        style="margin-top: 0"
        v-if="showTime || $route.name === 'previewReport'"
        inline
        size="small"
        class="head-form"
      >
        <el-form-item label="起止时间" style="margin-bottom: 0">
          <el-date-picker
            @change="changeDate"
            v-model="layoutData.time"
            type="datetimerange"
            value-format="timestamp"
            :picker-options="pickerOptions"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div
        class="ps-r border-r5 layout-row"
        v-for="(row, rowIndex) in layoutData.children"
        :key="rowIndex"
      >
        <div
          class="w100"
          :style="rowStyle(row)"
          v-if="row.changeType !== 'delete'"
        >
          <div
            class="ps-r col-box"
            :class="{ pad0: row.initHeight != '0' && row.initHeight <= 100 }"
            :style="
              previewColStyle({
                width: col.initCol,
                height:
                  (col.colHeight || row.initHeight) <= 100 &&
                  (col.colHeight || row.initHeight) !== 0
                    ? parseInt(col.colHeight || row.initHeight)
                    : (col.colHeight || row.initHeight) == 0
                    ? 'auto'
                    : parseInt(col.colHeight || row.initHeight) + 56,
                baseHeight: 1,
                componentName: col.componentName,
              })
            "
            v-for="(col, colIndex) in row.children"
            :key="colIndex"
          >
            <template v-if="col.changeType !== 'delete'">
              <div
                class="col-title"
                v-if="
                  col.componentName !== 'title-title' &&
                  col.componentName !== 'text-description'
                "
              >
                <span class="main-front">{{ col.mainTitle }}</span>
                <span class="secondary-front"
                  >&nbsp;&nbsp;{{ col.secondTitle }}</span
                >
                <span
                  v-if="
                    col.dataKey === 'common' && col.componentData.url.length > 0
                  "
                  class="detail-btn"
                  @click.stop="
                    changeRoute(col.componentData ? col.componentData.url : [])
                  "
                  >{{ col.componentData.linkText || '详情' }}</span
                >
              </div>

              <default-container v-if="col.componentName">
                <component
                  v-if="!Array.isArray(col.api) || col.api.length === 1"
                  :height="row.initHeight"
                  :mainTitle="col.mainTitle"
                  :is="`custom-report-custom-report-component-${col.componentName}`"
                  :dataKey="col.dataKey"
                  :time="layoutData.time"
                  :changeSize="changeSize"
                  :componentKey="col.componentKey"
                  :componentData="col.componentData"
                  :interval="col.interval"
                  :api="!Array.isArray(col.api) ? col.api : col.api[0]"
                  :method="col.method || 'get'"
                  :mixinParam="mixinParam"
                  @dataReady="dataReady(col)"
                />
                <el-tabs
                  v-if="Array.isArray(col.api) && col.api.length > 1"
                  type="border-card"
                  tab-position="bottom"
                  @tab-click="changeComTab($event, col)"
                >
                  <el-tab-pane
                    v-for="(item, apiIndex) in col.api"
                    :key="apiIndex"
                    :label="item.label ? item.label : ''"
                  >
                    <component
                      v-if="item.dsName"
                      :mainTitle="col.mainTitle"
                      :is="`custom-report-custom-report-component-${col.componentName}`"
                      :dataKey="col.dataKey"
                      :componentData="col.componentData"
                      :api="col.api[apiIndex]"
                      :method="col.method || 'get'"
                      :changeSize="changeSize"
                      :changeData="changeData"
                      :interval="col.interval"
                      @changeTableProp="
                        changeTableProp(col.componentData, $event)
                      "
                      :mixinParam="mixinParam"
                      :time="layoutData.time"
                    />
                  </el-tab-pane>
                </el-tabs>
              </default-container>
              <default-container v-else>
                <div class="w100 empty-box">空组件</div>
              </default-container>
            </template>
          </div>
        </div>
      </div>
    </div>

    <span
      v-if="isEditPath"
      :style="floatBox"
      class="cur-p ps-a t0 ps-icon save-icon"
    >
      <el-tooltip class="item" effect="dark" content="保存" placement="left">
        <img
          @click="handleSaveLayout(false)"
          width="60"
          class="cur-p ps-a t0 ps-icon save-icon"
          src="../../../../../static/images/reportMgr/icon/save.svg"
        />
      </el-tooltip>
    </span>
  </div>
</template>

<script>
import defaultContainer from '../components/custom-report/default-container.vue'
import customReports from './index.js';
import nt from '../../network';

export default {
  name: 'previewReport',
  props: [
    'chartLayoutName',
    'mixinParam',
    'showTime',
    'dateRange',
    'defaultTime',
  ],
  components: { defaultContainer, ...customReports },
  data() {
    return {
      breadArr: [
        { name: '我的报表' },
        { name: '报表列表', url: '/business/reportmgr/customReportList' },
        {
          name: '报表编辑',
          url: '/business/reportmgr/dragReport/' + this.chartLayoutName,
        },
        {
          name: '报表预览',
          url: '/business/reportmgr/previewReport/' + this.chartLayoutName,
        },
      ],
      fromListBread: [
        { name: '我的报表' },
        { name: '报表列表', url: '/business/reportmgr/customReportList' },
        {
          name: '报表预览',
          url: '/business/reportmgr/previewReport/' + this.chartLayoutName,
        },
      ],
      shortcuts: [
        {
          text: '最近10分钟',
          dateRange: 10 * 60 * 1000,
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 10 * 60 * 1000)
            $emit(picker, 'pick', [start, end])
          },
        },
        {
          text: '最近30分钟',
          dateRange: 30 * 60 * 1000,
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 30 * 60 * 1000)
            $emit(picker, 'pick', [start, end])
          },
        },
        {
          text: '最近1小时',
          dateRange: 3600 * 1000,
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000)
            $emit(picker, 'pick', [start, end])
          },
        },
        {
          text: '最近12小时',
          dateRange: 3600 * 1000 * 12,
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 12)
            $emit(picker, 'pick', [start, end])
          },
        },
        {
          text: '最近24小时',
          dateRange: 3600 * 1000 * 24,
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            $emit(picker, 'pick', [start, end])
          },
        },
        {
          text: '最近1周',
          dateRange: 3600 * 1000 * 24 * 7,
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            $emit(picker, 'pick', [start, end])
          },
        },
        {
          text: '最近30天',
          dateRange: 3600 * 1000 * 24 * 30,
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            $emit(picker, 'pick', [start, end])
          },
        },
      ],
      pickerOptions: {
        shortcuts: [],
        disabledDate: (today) => {
          if (
            !this.dateRange ||
            !this.dateRange.startLine ||
            !this.dateRange.endLine
          )
            return false
          if (
            today > this.dateRange.startLine &&
            today < this.dateRange.endLine
          )
            return false
          return true
        },
      },
      intervalTime: 0,
      intervalList: [
        {
          label: '不刷新',
          value: 0,
        },
        {
          label: '每半分钟刷新',
          value: 30 * 1000,
        },
        {
          label: '每1分钟刷新',
          value: 60 * 1000,
        },
        {
          label: '每5分钟刷新',
          value: 5 * 60 * 1000,
        },
        {
          label: '每10分钟刷新',
          value: 10 * 60 * 1000,
        },
      ],
      changeData: '',
      changeSize: '',
      isLoading: false,
      isSaved: false,
      isEditPath: false,
      editBtnTop: 50,
      styleForm: {},
      layoutData: {
        title: '',
        children: [],
      },
      queryData: {},
    }
  },
  watch: {
    defaultTime() {
      this.layoutData['time'] = JSON.parse(JSON.stringify(this.defaultTime))
    },
    dateRange: 'filterShortcuts',
  },
  computed: {
    floatBox() {
      return { top: `${this.editBtnTop}px` }
    },
  },
  methods: {
    dataReady(col) {
      col.isDataReady = true
      for (let rowItem of this.layoutData.children) {
        for (let colItem of rowItem.children) {
          if (!colItem.isDataReady && colItem.previewImage) {
            return
          }
        }
      }
      this.$emit( 'dataReady')
    },
    filterShortcuts() {
      if (!this.dateRange) {
        this.pickerOptions.shortcuts = this.shortcuts
      } else {
        let time = new Date().getTime()
        this.pickerOptions.shortcuts = this.shortcuts.filter(
          (item) => item.dateRange <= time - this.dateRange.startLine
        )
      }
    },
    changeComTab(tab, col) {
      this.changeSize = new Date()
      col.mainTitle = tab.label
    },
    resize() {
      this.changeSize = new Date()
    },
    previewColStyle(
      {
        width,
        height,
        baseWidth = 100,
        baseHeight = 3,
        layoutRow = 24,
        componentName,
      },
      mixinStyle = {}
    ) {
      if (
        componentName !== 'title-title' &&
        componentName !== 'text-description'
      ) {
        if (componentName) {
          width = `calc(${(baseWidth * width) / layoutRow}% - 57px)`
        } else {
          if (height <= 100 && height != 0) {
            width = `calc(${(baseWidth * width) / layoutRow}% - 17px)`
          } else {
            width = `calc(${(baseWidth * width) / layoutRow}% - 57px)`
          }
        }
      } else {
        width = `calc(${(baseWidth * width) / layoutRow}% - 17px)`
      }
      return {
        width,
        height: `${height / baseHeight}px`,
        // height: height>0?`${height / baseHeight}px`:'auto',
        ...mixinStyle,
      }
    },
    changeRoute(url) {
      if (url.length > 0) {
        this.$router.push(url[url.length - 1])
      }
    },
    rowStyle(row) {
      return {
        justifyContent: row.align,
        height: `${row.initHeight == 0 ? 300 : row.initHeight} px`,
      }
      // if (row.initHeight != 0) {
      //   if (row.children[0].componentName !== 'title-title') {
      //     return { justifyContent: row.align, height: parseInt(row.initHeight) + 56 + 'px' }
      //   } else {
      //     return { justifyContent: row.align, height: row.initHeight + 'px' }
      //   }
      // } else {
      //   return { justifyContent: row.align }
      // }
    },
    handleSaveLayout(callback) {
      let that = this
      let chartLayoutContent = JSON.parse(JSON.stringify(that.layoutData))
      chartLayoutContent.children.forEach((rowItem) => {
        rowItem.children.forEach((colItem) => {
          colItem.api = null
        })
      })
      nt.doRequest({
        method: 'post',
        uri: 'paas/chart-layout/v2/chart/chartLayout/save',
        data: {
          params: chartLayoutContent,
        },
        onSuccess: (response) => {
          this.$message.success(response.data.content)
          this.isSaved = true
          if (callback) {
            callback()
          } else {
            setTimeout(() => {
              this.$router.push('/business/reportmgr/customReportList')
            }, 1500)
          }
        },
      })
    },
    renderReport() {
      return new Promise((resolve, reject) => {
        this.isEditPath = this.$route.query.isEditPath || false
        // 在这里查询出布局，如果 isEditPath 为 true，则代表是从编辑页面跳转过来的
        // 这个时候布局还未保存到数据库（因为保存到数据库之前要先预览布局）
        // 遂直接从路由参数获取，若 isEditPath 为 false 布局从数据库获取
        if (this.isEditPath) {
          let data = localStorage.getItem('drag-report-data')
          this.layoutData = JSON.parse(data)
        } else {
          this.isLoading = true
          nt.doRequest({
            method: 'post',
            uri: '/paas/chart-layout/v2/chart/getByName',
            data: {
              params: this.chartLayoutName,
            },
            onSuccess: (resp) => {
              if (resp.data.content) {
                this.layoutData = resp.data.content
                if (this.defaultTime) {
                  this.layoutData['time'] = JSON.parse(
                    JSON.stringify(this.defaultTime)
                  )
                }
              }
              this.isLoading = false
            },
            onError: (resp) => {
              this.isLoading = false
            },
          })
        }
        resolve()
      })
    },
    addListener() {
      this.$listeners = { scroll: null }
      this.$listeners.scroll = this.handleListenerScroll
      window.addEventListener('scroll', this.$listeners.scroll, true)
    },
    handleListenerScroll(e) {
      let scrollTop
      if (e.target.className?.indexOf('preview-report') > -1) {
        scrollTop = e.target.scrollTop
      }
      this.editBtnTop = scrollTop + 50
    },
    changeDate(time) {
      this.$emit( 'changeDate', time)
    },
  },
  mounted() {
    this.filterShortcuts()
    this.addListener()
    this.renderReport()
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == '/login') {
      next()
      return
    }
    if (!this.layoutData) {
      next()
      return
    }
    if (this.isEditPath && !this.isSaved) {
      setTimeout(() => {
        this.$confirm('即将离开此页面，是否保存已编辑的布局？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.handleSaveLayout(next)
            return
          })
          .catch(() => {
            next()
            return
          })
      }, 500)
    } else {
      next()
      return
    }
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.$listeners.scroll)
  },
  emits: ['pick', 'changeDate', 'dataReady'],
}
</script>

<style>
.preview-report .el-tabs--border-card > .el-tabs__content {
  padding: 0;
  height: calc(100% - 35px);
}
.preview-report .el-tabs__item {
  height: 25px;
  line-height: 25px;
}
.preview-report .el-tabs--border-card > .el-tabs__content .el-tab-pane {
  height: 100%;
}
.preview-report .el-tabs__nav-next,
.preview-report .el-tabs__nav-prev {
  line-height: 25px;
}
.preview-report .el-card__body {
  box-sizing: border-box;
}
</style>

<style lang="scss" scoped>
.detail-btn {
  position: absolute;
  cursor: pointer;
  right: 20px;
  top: 10px;
  color: #419eff;
}

.el-tabs {
  width: 100%;
  height: 100%;
  border: none;
  box-shadow: none;
}

.el-slider {
  width: 200px;
}

.head-form {
  margin-top: 15px;
  margin-left: 15px;
}

.empty-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pad0 {
  padding: 0px !important;
}

.col-title {
  padding: 18px 0px 10px;
}

.main-front {
  font-size: 14px;
  color: #6d7c8b;
  font-weight: bold;
}

.secondary-front {
  font-size: 12px;
  color: #a3adb6;
}

.preview-report .edit {
  display: none;
  position: absolute;
  top: 5px;
  right: 5px;
}

.preview-report .col-box:hover .edit {
  display: block;
}

@import '../styles/global.scss';
@import './layout.scss';
</style>
